// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({env: 'cloud1-5glocnmp62950062'})
const db = cloud.database()
const $ = db.command.aggregate
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID
  const key = event.key
  let time = 0
  let result = db.collection('searchkeys').where({key: key}).get()
  if((await result).data.length==0){
    db.collection('searchkeys').add({
      data:{
        key: key,
        time: 1
      }
    })
  }else{
    time= (await result).data[0].time+1
    let id = (await result).data[0]._id
    db.collection('searchkeys').doc(id).update({
      data:{
        time: time
      }
    })
  }
  const dynamiclist = await db.collection('dynamiclist').aggregate().match(
    db.command.or([
      {
      title: db.RegExp({
        regexp: key,
        options: 'i'
      })
    },
    {
      content: db.RegExp({
        regexp: key,
        options: 'i'
      })
    }
  ])
).lookup({
  from: 'loveList',
  let:{
    dynamic_id:'$_id'
  },
  pipeline: $.pipeline()
  .match(_.expr($.and([
    $.eq(['$dynamicid','$$dynamic_id']),
    $.eq(['$openid',openid]),
    $.eq(['$status',true])
  ]))).done(),
   as:'love'
}).end()
const tasklist = await db.collection('tasklist').aggregate().match(db.command.or([
  {
  title: db.RegExp({
    regexp: key,
    options: 'i'
  })
},
{
  desc: db.RegExp({
    regexp: key,
    options: 'i'
  })
}
]
).and({status:false})).lookup({
    from: 'applyTask',
    localField:'_id',
    foreignField:'taskid',
    as:'applyData'
  }).end()
const teamlist = await db.collection('teamlist').limit(20).where(
  db.command.or([
    {
    teamname: db.RegExp({
      regexp: key,
      options: 'i'
    })
  },
  {
    requirement: db.RegExp({
      regexp: key,
      options: 'i'
    })
  }
])
).get()
const internlist = await db.collection('internlist').limit(20).where(
  db.command.or([
    {
    title: db.RegExp({
      regexp: key,
      options: 'i'
    })
  },
  {
    company: db.RegExp({
      regexp: key,
      options: 'i'
    })
  },
  {
    desc: db.RegExp({
      regexp: key,
      options: 'i'
    })
  },

])
).get()

  return {
    event,
    time,
    dynamiclist,
    tasklist,
    teamlist,
    internlist
  }
}